﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using Emgu.CV.CvEnum;
using System.Security.Cryptography;

class Program
{
    [DllImport("user32.dll")]
    private static extern bool SetCursorPos(int x, int y);

    [DllImport("user32.dll")]
    private static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;

    static void Main(string[] args)
    {
        // 加载模板图片
        string templatePath = @"path\to\your\template.png"; // 替换为你的模板图片路径
        Image<Bgr, byte> templateImage = new Image<Bgr, byte>(templatePath);
        templateImage = templateImage.Resize(60, 60, Inter.Cubic); // 调整模板大小以匹配屏幕分辨率或需要的大小
        MCvScalar color = new MCvScalar(255); // 模板匹配的颜色值，通常为白色或其他高对比色
        Image<Gray, byte> templateGray = templateImage.Convert<Gray, byte>();


        Image<Gray, float> result = new Image<Gray, float>(null, screenGray.Width - templateGray.Width + 1, screenGray.Height - templateGray.Height + 1);
        CvInvoke.MatchTemplate(screenGray, templateGray, result, TemplateMatchingType.CcoeffNormed);
        double minVal, maxVal;
        Point minLoc, maxLoc;
        CvInvoke.MinMaxLoc(result, out minVal, out maxVal, out minLoc, out maxLoc); // 获取最大匹配值的位置和值


        // 获取屏幕截图
        using (Image<Bgr, byte> screen = new Image<Bgr, byte>("Screenshot.jpg")) // 使用截图工具或代码生成截图并保存为Screenshot.jpg
        {
            Image<Gray, byte> screenGray = screen.Convert<Gray, byte>();
            // 使用模板匹配找到图片位置
            MCvPoint matchedPoint = CvInvoke.FindHomography(templateGray, screenGray, TemplateMatchingType.CcoeffNormed);
            if (matchedPoint != null)
            {
                Console.WriteLine("匹配成功！位置: " + matchedPoint);
                // 移动鼠标到匹配位置并点击
                SetCursorPos(matchedPoint.X + templateImage.Width / 2, matchedPoint.Y + templateImage.Height / 2); // 中心点位置
                mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); // 按下鼠标左键
                mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); // 释放鼠标左键
            }
            else
            {
                Console.WriteLine("未找到匹配的图片");
            }
        }
    }
}